import { ref } from 'vue'
import { defineStore } from "pinia"

export const useHomeStore = defineStore('home', () => {
  const isCollapse = ref(false)
  const selectMenu = ref([])
  const routerList = ref([])
  const menuActive = ref('1-1')

  const collapseMenu = () => {
    isCollapse.value = !isCollapse.value
  }

  const addMenu = (playload) => {
    if (selectMenu.value.findIndex(item => item.path === playload.path) === -1) {
      selectMenu.value.push(playload)
    }
  }

  const closeMenu = (playload) => {
    // 找到点击数据的索引
    const index = selectMenu.value.findIndex(val => val.name === playload.name)
    // 通过索引删除数组的指定元素
    selectMenu.value.splice(index, 1)
  }

  const dynamicMenu = (playload) => {
    const moudles = import.meta.glob('../views/**/**/*.vue')
    console.log(moudles) 

    function routerSet(router) {
       router.forEach(route => {
         // 判断没有子菜单 拼接路由数据
         if(!route.children) {
            const url = `../views${route.meta.path}/index.vue`
            // 拿到获取的vue组件 
            route.component = moudles[url]
         } else {
          routerSet(route.children)
         }
       })
    }
    routerSet(playload)
    // 拿到完整的路由数据
    routerList.value = playload
  }

  const updateMenuActive = (playload) => {
    menuActive.value = playload
  }

  return {
    routerList,
    isCollapse,
    selectMenu,
    menuActive,
    collapseMenu,
    addMenu,
    closeMenu,
    dynamicMenu,
    updateMenuActive
  }
},
{
  persist: true
}
)